/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.supplier.modular.structure.user.service.impl;

import cn.afterturn.easypoi.cache.manager.POICacheManager;
import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhs.trans.service.impl.TransService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.supplier.core.enums.SupplierBuildInEnum;
import vip.xiaonuo.supplier.core.enums.SupplierDataTypeEnum;
import vip.xiaonuo.supplier.modular.structure.org.entity.SupplierOrg;
import vip.xiaonuo.supplier.modular.structure.org.service.SupplierOrgService;
import vip.xiaonuo.supplier.modular.structure.position.entity.SupplierPosition;
import vip.xiaonuo.supplier.modular.structure.position.service.SupplierPositionService;
import vip.xiaonuo.supplier.modular.structure.relation.entity.SupplierRelation;
import vip.xiaonuo.supplier.modular.structure.relation.enums.SupplierRelationCategoryEnum;
import vip.xiaonuo.supplier.modular.structure.relation.service.SupplierRelationService;
import vip.xiaonuo.supplier.modular.structure.resource.entity.SupplierButton;
import vip.xiaonuo.supplier.modular.structure.resource.entity.SupplierMenu;
import vip.xiaonuo.supplier.modular.structure.resource.service.SupplierButtonService;
import vip.xiaonuo.supplier.modular.structure.resource.service.SupplierMenuService;
import vip.xiaonuo.supplier.modular.structure.role.entity.SupplierRole;
import vip.xiaonuo.supplier.modular.structure.role.service.SupplierRoleService;
import vip.xiaonuo.supplier.modular.structure.user.entity.SupplierUser;
import vip.xiaonuo.supplier.modular.structure.user.enums.SupplierRoleCategoryEnum;
import vip.xiaonuo.supplier.modular.structure.user.enums.SupplierUserStatusEnum;
import vip.xiaonuo.supplier.modular.structure.user.mapper.SupplierUserMapper;
import vip.xiaonuo.supplier.modular.structure.user.param.*;
import vip.xiaonuo.supplier.modular.structure.user.result.SupplierUserExportResult;
import vip.xiaonuo.supplier.modular.structure.user.result.SupplierUserOwnResourceResult;
import vip.xiaonuo.supplier.modular.structure.user.result.SupplierUserRoleResult;
import vip.xiaonuo.supplier.modular.structure.user.service.SupplierUserService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.excel.CommonExcelCustomMergeStrategy;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.util.*;
import vip.xiaonuo.dev.api.DevConfigApi;
import vip.xiaonuo.sys.api.SysRoleApi;
import vip.xiaonuo.sys.api.SysUserApi;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 人员Service接口实现类
 *
 * @author xuyuxiang
 * @date 2022/2/23 18:43
 **/
@Service
public class SupplierUserServiceImpl extends ServiceImpl<SupplierUserMapper, SupplierUser> implements SupplierUserService {

    private static final String SNOWY_SYS_DEFAULT_PASSWORD_KEY = "SNOWY_SYS_DEFAULT_PASSWORD";

    @Resource
    private TransService transService;

    @Resource
    private DevConfigApi devConfigApi;

    @Resource
    private SysUserApi sysUserApi;

    @Resource
    private SysRoleApi sysRoleApi;

    @Resource
    private SupplierOrgService supplierOrgService;

    @Resource
    private SupplierPositionService supplierPositionService;

    @Resource
    private SupplierRelationService supplierRelationService;

    @Resource
    private SupplierMenuService supplierMenuService;

    @Resource
    private SupplierButtonService supplierButtonService;

    @Resource
    private SupplierRoleService supplierRoleService;

    private List<String> childRoldList = new ArrayList<>();

    @Override
    public Page<SupplierUser> page(SupplierUserPageParam supplierUserPageParam) {
        QueryWrapper<SupplierUser> queryWrapper = new QueryWrapper<SupplierUser>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(supplierUserPageParam.getSearchKey())) {
            queryWrapper.lambda().and(q -> q.like(SupplierUser::getAccount, supplierUserPageParam.getSearchKey())
                    .or().like(SupplierUser::getName, supplierUserPageParam.getSearchKey()));
        }
        if (ObjectUtil.isNotEmpty(supplierUserPageParam.getOrgId())) {
            List<String> childOrgIdList = CollStreamUtil.toList(supplierOrgService.getChildListById(supplierOrgService
                    .getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId()), supplierUserPageParam.getOrgId(), true), SupplierOrg::getId);
            if (ObjectUtil.isNotEmpty(childOrgIdList)) {
                queryWrapper.lambda().in(SupplierUser::getOrgId, childOrgIdList);
            } else {
                return new Page<>();
            }
//            queryWrapper.lambda().eq(SupplierUser::getOrgId, supplierUserPageParam.getOrgId());
        }
        if (ObjectUtil.isNotEmpty(supplierUserPageParam.getUserStatus())) {
            queryWrapper.lambda().eq(SupplierUser::getUserStatus, supplierUserPageParam.getUserStatus());
        }

        if (ObjectUtil.isAllNotEmpty(supplierUserPageParam.getSortField(), supplierUserPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(supplierUserPageParam.getSortOrder());
            queryWrapper.orderBy(true, supplierUserPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(supplierUserPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SupplierUser::getSortCode);
        }
        // 排除超管
        queryWrapper.lambda().ne(SupplierUser::getAccount, SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
        //需要排除自己
        queryWrapper.lambda().ne(SupplierUser::getId, StpLoginUserUtil.getLoginUser().getId());

        //需要防越级，只能管理角色级别比自己低的人员，先查出全部角色
        //Mr.wu 加上数据归属，只查询本单位的角色
        List<SupplierRole> allRoleList = supplierRoleService.list(new LambdaQueryWrapper<SupplierRole>().eq(SupplierRole::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId()));
        List<String> allRoleIdList = allRoleList.stream().map(SupplierRole::getId).collect(Collectors.toList());
        //1、先获取操作员当前角色
        SupplierUserIdParam supplierUserIdParam = new SupplierUserIdParam();
        supplierUserIdParam.setId(StpLoginUserUtil.getLoginUser().getId());
        List<String> ownRoleList = this.ownRole(supplierUserIdParam);//获取当前用户的角色数组
        List<String> childRoleIds = getChildRole(allRoleList, ownRoleList);//获取下级角色数据
        LambdaQueryWrapper<SupplierRelation> relationLambdaQueryWrapperQueryWrapper = new LambdaQueryWrapper<>();

        LambdaQueryWrapper<SupplierRelation> allSysRelationQueryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(allRoleIdList)) {
            allSysRelationQueryWrapper.in(SupplierRelation::getTargetId, allRoleIdList);//本公司已经授权的用户集合
        }
        List<String> allObjectList = supplierRelationService.list(allSysRelationQueryWrapper).stream().map(SupplierRelation::getObjectId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(childRoleIds)) {
            relationLambdaQueryWrapperQueryWrapper.select(SupplierRelation::getId, SupplierRelation::getObjectId, SupplierRelation::getTargetId, SupplierRelation::getCategory, SupplierRelation::getExtJson).in(SupplierRelation::getTargetId, childRoleIds).eq(SupplierRelation::getCategory, SupplierRelationCategoryEnum.SYS_USER_HAS_ROLE.getValue());
            List<String> objectList = supplierRelationService.list(relationLambdaQueryWrapperQueryWrapper).stream().map(SupplierRelation::getObjectId).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(objectList)) {
                if (ObjectUtil.isNotEmpty(allObjectList)) {
                    queryWrapper.lambda().and(i -> i.in(SupplierUser::getId, objectList).or().notIn(SupplierUser::getId, allObjectList));//获取未被授权或由当前操作员授权的子用户的用户
                } else {
                    queryWrapper.lambda().and(i -> i.in(SupplierUser::getId, objectList));//获取未被授权或由当前操作员授权的子用户的用户
                }
            }
        } else {
            if (ObjectUtil.isNotEmpty(allObjectList)) {
                queryWrapper.lambda().and(i -> i.notIn(SupplierUser::getId, allObjectList));//尚未授权的用户信息
            }
        }
        //排序
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.lambda().in(SupplierUser::getOrgId, loginUserDataScope);
        } else {
            queryWrapper.lambda().eq(SupplierUser::getId, StpUtil.getLoginIdAsString());
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SupplierUserAddParam supplierUserAddParam) {
        checkParam(supplierUserAddParam);
        SupplierUser supplierUser = BeanUtil.toBean(supplierUserAddParam, SupplierUser.class);
        //数据归属
        supplierUser.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isEmpty(supplierUser.getAvatar())) {
            // 设置默认头像
            supplierUser.setAvatar(CommonAvatarUtil.generateImg(supplierUser.getName()));
        }
        // 设置密码
        supplierUser.setPassword(CommonCryptogramUtil.doHashValue(devConfigApi.getValueByKey(SNOWY_SYS_DEFAULT_PASSWORD_KEY)));
        // 设置状态
        supplierUser.setUserStatus(SupplierUserStatusEnum.ENABLE.getValue());
        this.save(supplierUser);

        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(SupplierDataTypeEnum.USER.getValue(), JSONUtil.createArray().put(supplierUser));
    }

    private void checkParam(SupplierUserAddParam supplierUserAddParam) {
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(supplierUserAddParam.getOrgId())) {
                throw new CommonException("您没有权限在该机构下增加人员，机构id：{}", supplierUserAddParam.getOrgId());
            }
        } else {
            throw new CommonException("您没有权限在该机构下增加人员，机构id：{}", supplierUserAddParam.getOrgId());
        }
        if (this.count(new LambdaQueryWrapper<SupplierUser>()
                .eq(SupplierUser::getAccount, supplierUserAddParam.getAccount())) > 0) {
            throw new CommonException("存在重复的账号，账号为：{}", supplierUserAddParam.getAccount());
        }
        if(ObjectUtil.isNotEmpty(supplierUserAddParam.getPhone())) {
            if(!PhoneUtil.isMobile(supplierUserAddParam.getPhone())) {
                throw new CommonException("手机号码：{}格式错误", supplierUserAddParam.getPhone());
            }
            if (this.count(new LambdaQueryWrapper<SupplierUser>()
                    .eq(SupplierUser::getPhone, CommonCryptogramUtil.doSm4CbcEncrypt(supplierUserAddParam.getPhone()))) > 0) {
                throw new CommonException("存在重复的手机号，手机号为：{}", supplierUserAddParam.getPhone());
            }
        }
        if(ObjectUtil.isNotEmpty(supplierUserAddParam.getEmail())) {
            if(!CommonEmailUtil.isEmail(supplierUserAddParam.getEmail())) {
                throw new CommonException("邮箱：{}格式错误", supplierUserAddParam.getEmail());
            }
            if (this.count(new LambdaQueryWrapper<SupplierUser>()
                    .eq(SupplierUser::getEmail, supplierUserAddParam.getEmail())) > 0) {
                throw new CommonException("存在重复的邮箱，邮箱为：{}", supplierUserAddParam.getEmail());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SupplierUserEditParam supplierUserEditParam) {
        SupplierUser supplierUser = this.queryEntity(supplierUserEditParam.getId());
        checkParam(supplierUserEditParam);
        boolean updateSuperAdminAccount = supplierUser.getAccount().equals(SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue()) &&
                !supplierUserEditParam.getAccount().equals(SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
        if(updateSuperAdminAccount) {
            throw new CommonException("不可修改系统内置超管人员账号");
        }
        BeanUtil.copyProperties(supplierUserEditParam, supplierUser);
        this.updateById(supplierUser);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(SupplierDataTypeEnum.USER.getValue(), JSONUtil.createArray().put(supplierUser));
    }

    private void checkParam(SupplierUserEditParam supplierUserEditParam) {
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(supplierUserEditParam.getOrgId())) {
                throw new CommonException("您没有权限编辑该机构下的人员，机构id：{}", supplierUserEditParam.getOrgId());
            }
        } else {
            if(!supplierUserEditParam.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限编辑该机构下的人员，机构id：{}", supplierUserEditParam.getOrgId());
            }
        }
        if (this.count(new LambdaQueryWrapper<SupplierUser>()
                .eq(SupplierUser::getAccount, supplierUserEditParam.getAccount())
                .ne(SupplierUser::getId, supplierUserEditParam.getId())) > 0) {
            throw new CommonException("存在重复的账号，账号为：{}", supplierUserEditParam.getAccount());
        }
        if(ObjectUtil.isNotEmpty(supplierUserEditParam.getPhone())) {
            if(!PhoneUtil.isMobile(supplierUserEditParam.getPhone())) {
                throw new CommonException("手机号码：{}格式错误", supplierUserEditParam.getPhone());
            }
            if (this.count(new LambdaQueryWrapper<SupplierUser>()
                    .eq(SupplierUser::getPhone, CommonCryptogramUtil.doSm4CbcEncrypt(supplierUserEditParam.getPhone()))
                    .ne(SupplierUser::getId, supplierUserEditParam.getId())) > 0) {
                throw new CommonException("存在重复的手机号，手机号为：{}", supplierUserEditParam.getPhone());
            }
        }
        if(ObjectUtil.isNotEmpty(supplierUserEditParam.getEmail())) {
            if(!CommonEmailUtil.isEmail(supplierUserEditParam.getEmail())) {
                throw new CommonException("邮箱：{}格式错误", supplierUserEditParam.getEmail());
            }
            if (this.count(new LambdaQueryWrapper<SupplierUser>()
                    .eq(SupplierUser::getEmail, supplierUserEditParam.getEmail())
                    .ne(SupplierUser::getId, supplierUserEditParam.getId())) > 0) {
                throw new CommonException("存在重复的邮箱，邮箱为：{}", supplierUserEditParam.getEmail());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SupplierUserIdParam> supplierUserIdParamList) {
        List<String> supplierUserIdList = CollStreamUtil.toList(supplierUserIdParamList, SupplierUserIdParam::getId);
        if(ObjectUtil.isNotEmpty(supplierUserIdList)) {
            boolean containsSuperAdminAccount = this.listByIds(supplierUserIdList).stream().map(SupplierUser::getAccount)
                    .collect(Collectors.toSet()).contains(SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
            if(containsSuperAdminAccount) {
                throw new CommonException("不可删除系统内置超管人员");
            }
            // 获取这些人员的的机构id集合
            Set<String> userOrgIdList = this.listByIds(supplierUserIdList).stream().map(SupplierUser::getOrgId).collect(Collectors.toSet());
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.containsAll(userOrgIdList)) {
                    throw new CommonException("您没有权限删除这些机构下的人员，机构id：{}",
                            CollectionUtil.subtract(userOrgIdList, loginUserDataScope));
                }
            } else {
                if(supplierUserIdList.size() != 1 || !supplierUserIdList.get(0).equals(StpUtil.getLoginIdAsString())) {
                    throw new CommonException("您没有权限删除这些机构下的人员，机构id：{}", userOrgIdList);
                }
            }
            // 清除【将这些人员作为主管】的信息
            this.update(new LambdaUpdateWrapper<SupplierUser>().in(SupplierUser::getDirectorId, supplierUserIdList).set(SupplierUser::getDirectorId, null));

            // 清除【将这些人员作为兼任岗位的主管】的信息
            this.list(new LambdaQueryWrapper<SupplierUser>() .isNotNull(SupplierUser::getPositionJson)).forEach(supplierUser -> {
                List<JSONObject> handledJsonObjectList = JSONUtil.toList(JSONUtil.parseArray(supplierUser.getPositionJson()),
                        JSONObject.class).stream().peek(jsonObject -> {
                    String directorId = jsonObject.getStr("directorId");
                    if (ObjectUtil.isNotEmpty(directorId) && supplierUserIdList.contains(directorId)) {
                        jsonObject.remove("directorId");
                    }
                }).collect(Collectors.toList());
                this.update(new LambdaUpdateWrapper<SupplierUser>().eq(SupplierUser::getId, supplierUser.getId())
                        .set(SupplierUser::getPositionJson, JSONUtil.toJsonStr(handledJsonObjectList)));
            });

            // 清除【将这些人员作为主管】的机构的主管信息
            supplierOrgService.update(new LambdaUpdateWrapper<SupplierOrg>().in(SupplierOrg::getDirectorId, supplierUserIdList).set(SupplierOrg::getDirectorId, null));

            // 执行删除
            this.removeByIds(supplierUserIdList);

            // 发布删除事件
            CommonDataChangeEventCenter.doDeleteWithDataId(SupplierDataTypeEnum.USER.getValue(), supplierUserIdList);
        }
    }

    @Override
    public SupplierUser detail(SupplierUserIdParam supplierUserIdParam) {
        return this.queryEntity(supplierUserIdParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void disableUser(SupplierUserIdParam supplierUserIdParam) {
        SupplierUser supplierUser = this.detail(supplierUserIdParam);
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(supplierUser.getOrgId())) {
                throw new CommonException("您没有权限禁用该机构下的人员：{}，机构id：{}", supplierUser.getName(), supplierUser.getOrgId());
            }
        } else {
            if(!supplierUser.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限禁用该机构下的人员：{}，机构id：{}", supplierUser.getName(), supplierUser.getOrgId());
            }
        }
        this.update(new LambdaUpdateWrapper<SupplierUser>().eq(SupplierUser::getId,
                supplierUserIdParam.getId()).set(SupplierUser::getUserStatus, SupplierUserStatusEnum.DISABLED.getValue()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void enableUser(SupplierUserIdParam supplierUserIdParam) {
        SupplierUser supplierUser = this.detail(supplierUserIdParam);
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(supplierUser.getOrgId())) {
                throw new CommonException("您没有权限启用该机构下的人员：{}，机构id：{}", supplierUser.getName(), supplierUser.getOrgId());
            }
        } else {
            if(!supplierUser.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限启用该机构下的人员：{}，机构id：{}", supplierUser.getName(), supplierUser.getOrgId());
            }
        }
        this.update(new LambdaUpdateWrapper<SupplierUser>().eq(SupplierUser::getId,
                supplierUserIdParam.getId()).set(SupplierUser::getUserStatus, SupplierUserStatusEnum.ENABLE.getValue()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void resetPassword(SupplierUserIdParam supplierUserIdParam) {
        SupplierUser supplierUser = this.detail(supplierUserIdParam);
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(supplierUser.getOrgId())) {
                throw new CommonException("您没有权限为该机构下的人员：{}重置密码，机构id：{}", supplierUser.getName(), supplierUser.getOrgId());
            }
        } else {
            if(!supplierUser.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限为该机构下的人员：{}重置密码，机构id：{}", supplierUser.getName(), supplierUser.getOrgId());
            }
        }
        this.update(new LambdaUpdateWrapper<SupplierUser>().eq(SupplierUser::getId,
                supplierUserIdParam.getId()).set(SupplierUser::getPassword,
                CommonCryptogramUtil.doHashValue(devConfigApi.getValueByKey(SNOWY_SYS_DEFAULT_PASSWORD_KEY))));
    }

    @Override
    public List<String> ownRole(SupplierUserIdParam supplierUserIdParam) {
        return sysUserApi.ownRole(supplierUserIdParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void grantRole(SupplierUserGrantRoleParam supplierUserGrantRoleParam) {
        SupplierUser supplierUser = this.queryEntity(supplierUserGrantRoleParam.getId());
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(supplierUser.getOrgId())) {
                throw new CommonException("您没有权限为该机构下的人员：{}授权角色，机构id：{}", supplierUser.getName(), supplierUser.getOrgId());
            }
        } else {
            if(!supplierUser.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限为该机构下的人员：{}授权角色，机构id：{}", supplierUser.getName(), supplierUser.getOrgId());
            }
        }
        sysUserApi.grantRole(supplierUserGrantRoleParam.getId(), supplierUserGrantRoleParam.getRoleIdList());
    }

    @Override
    public SupplierUserOwnResourceResult ownResource(SupplierUserIdParam supplierUserIdParam) {
        SupplierUserOwnResourceResult supplierUserOwnResourceResult = new SupplierUserOwnResourceResult();
        supplierUserOwnResourceResult.setId(supplierUserIdParam.getId());
        supplierUserOwnResourceResult.setGrantInfoList(supplierRelationService.getRelationListByObjectIdAndCategory(supplierUserIdParam.getId(),
                SupplierRelationCategoryEnum.SYS_USER_HAS_RESOURCE.getValue()).stream().map(sysRelation ->
                JSONUtil.toBean(sysRelation.getExtJson(), SupplierUserOwnResourceResult.SupplierUserOwnResource.class)).collect(Collectors.toList()));
        return supplierUserOwnResourceResult;
    }

    @Override
    public void grantResource(SupplierUserGrantResourceParam supplierUserGrantResourceParam) {
        List<String> menuIdList = supplierUserGrantResourceParam.getGrantInfoList().stream()
                .map(SupplierUserGrantResourceParam.SupplierUserGrantResource::getMenuId).collect(Collectors.toList());
//        if(ObjectUtil.isNotEmpty(menuIdList)) {
//            SupplierUserIdParam supplierUserIdParam = new SupplierUserIdParam();
//            supplierUserIdParam.setId(sysUserGrantResourceParam.getId());
//            List<String> roleIdList = this.ownRole(supplierUserIdParam);
//            Set<String> sysModuleIdList = sysMenuService.listByIds(menuIdList).stream().map(SysMenu::getModule).collect(Collectors.toSet());
//            boolean containsSystemModule = sysModuleService.listByIds(sysModuleIdList).stream().map(SysModule::getCode)
//                .collect(Collectors.toSet()).contains(SysBuildInEnum.BUILD_IN_MODULE_CODE.getValue());
//            if(containsSystemModule) {
//                if(ObjectUtil.isEmpty(roleIdList)) {
//                    throw new CommonException("非超管角色用户不可被授权系统模块菜单资源");
//                } else {
//                    boolean hasSuperAdminRole = sysRoleService.listByIds(roleIdList).stream().map(SysRole::getCode).collect(Collectors.toSet())
//                        .contains(SysBuildInEnum.BUILD_IN_ROLE_CODE.getValue());
//                    if(!hasSuperAdminRole) {
//                        throw new CommonException("非超管角色用户不可被授权系统模块菜单资源");
//                    }
//                }
//            }
//        }
        List<String> extJsonList = supplierUserGrantResourceParam.getGrantInfoList().stream()
                .map(JSONUtil::toJsonStr).collect(Collectors.toList());
        //提取menu对应的page权限字符
        List<String> targetList = new ArrayList<>();
        menuIdList.forEach(menuId->{
            SupplierMenu supplierMenu = supplierMenuService.queryEntity(menuId);
            if(ObjectUtil.isNotEmpty(supplierMenu.getCode())) {
                List<String> codes = List.of(supplierMenu.getCode().split(","));
                codes.forEach(code ->{
                    if(ObjectUtil.isNotEmpty(supplierMenu.getPath()) && !targetList.contains(code)){
                        targetList.add("/" + code);
                    }
                });
            }
        });
        //提取按钮对应的权限字符串
        supplierUserGrantResourceParam.getGrantInfoList().stream().map(SupplierUserGrantResourceParam.SupplierUserGrantResource::getButtonInfo).forEach((List<String> buttonList)->{
            buttonList.stream().forEach((String buttonId)->{
                SupplierButton supplierButton = supplierButtonService.queryEntity(buttonId);
                if(ObjectUtil.isNotEmpty(supplierButton.getComponent())) {
                    List<String> components = List.of(supplierButton.getComponent().split(","));
                    components.forEach(component -> {
                        if (ObjectUtil.isNotEmpty(component) && !targetList.contains("/" + component)) {
                            targetList.add("/" + component);
                        }
                    });
                }
                //20241218改支持多个后端权限
//                if(ObjectUtil.isNotEmpty(sysButtonService.queryEntity(buttonId).getComponent()) && !targetList.contains("/"+sysButtonService.queryEntity(buttonId).getComponent())){
//                    targetList.add("/"+sysButtonService.queryEntity(buttonId).getComponent());
//                }
            });
        });
        List<String> extJsonListP = new ArrayList<>();
        targetList.forEach(menuAndButtonId->{
            JSONObject ext = new JSONObject();
            List<String> orgList = new ArrayList<>();
            ext.set("apiUrl",menuAndButtonId);
            ext.set("scopeCategory","SCOPE_ALL");
            ext.set("scopeDefineOrgIdList",orgList);
            extJsonListP.add(ext.toString());
        });

        supplierRelationService.saveRelationBatchWithClear(supplierUserGrantResourceParam.getId(), menuIdList, SupplierRelationCategoryEnum.SYS_USER_HAS_RESOURCE.getValue(), extJsonList);
        supplierRelationService.saveRelationBatchWithClear(supplierUserGrantResourceParam.getId(), targetList, SupplierRelationCategoryEnum.SYS_USER_HAS_PERMISSION.getValue(),
                extJsonListP);//保存后端权限
    }

    @Override
    public void exportUser(SupplierUserExportParam supplierUserExportParam, HttpServletResponse response) throws IOException {
        File tempFile = null;
        try {
            QueryWrapper<SupplierUser> queryWrapper = new QueryWrapper<SupplierUser>().checkSqlInjection();
            // 排除超管
            queryWrapper.lambda().ne(SupplierUser::getAccount, SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                queryWrapper.lambda().in(SupplierUser::getOrgId, loginUserDataScope);
            } else {
                queryWrapper.lambda().eq(SupplierUser::getId, StpUtil.getLoginIdAsString());
            }
            if(ObjectUtil.isNotEmpty(supplierUserExportParam.getUserIds())) {
                queryWrapper.lambda().in(SupplierUser::getId, StrUtil.split(supplierUserExportParam.getUserIds(), StrUtil.COMMA));
            } else {
                if (ObjectUtil.isNotEmpty(supplierUserExportParam.getSearchKey())) {
                    queryWrapper.lambda().and(q -> q.like(SupplierUser::getAccount, supplierUserExportParam.getSearchKey())
                            .or().like(SupplierUser::getName, supplierUserExportParam.getSearchKey())
                            .or().like(SupplierUser::getPhone, supplierUserExportParam.getSearchKey()));
                }
                if (ObjectUtil.isNotEmpty(supplierUserExportParam.getUserStatus())) {
                    queryWrapper.lambda().eq(SupplierUser::getUserStatus, supplierUserExportParam.getUserStatus());
                }
            }
            String fileName = "SNOWY系统B端人员信息清单.xlsx";
            List<SupplierUser> supplierUserList = this.list(queryWrapper);
            if(ObjectUtil.isEmpty(supplierUserList)) {
                throw new CommonException("无数据可导出");
            }
            transService.transBatch(supplierUserList);
            supplierUserList = CollectionUtil.sort(supplierUserList, Comparator.comparing(SupplierUser::getOrgId));
            List<SupplierUserExportResult> supplierUserExportResultList = supplierUserList.stream()
                    .map(supplierUser -> {
                        SupplierUserExportResult supplierUserExportResult = new SupplierUserExportResult();
                        BeanUtil.copyProperties(supplierUser, supplierUserExportResult);
                        supplierUserExportResult.setGroupName(ObjectUtil.isNotEmpty(supplierUserExportResult.getOrgName())?
                                supplierUserExportResult.getOrgName():"无组织");
                        // 状态枚举转为文字
                        supplierUserExportResult.setUserStatus(supplierUserExportResult.getUserStatus()
                                .equalsIgnoreCase(SupplierUserStatusEnum.ENABLE.getValue())?"正常":"停用");
                        // 将base64转为byte数组
                        if (ObjectUtil.isNotEmpty(supplierUser.getAvatar())) {
                            supplierUserExportResult.setAvatar(ImgUtil.toBytes(ImgUtil.toImage(StrUtil
                                    .split(supplierUser.getAvatar(), StrUtil.COMMA).get(1)), ImgUtil.IMAGE_TYPE_PNG));
                        }
                        return supplierUserExportResult;
                    }).collect(Collectors.toList());
            // 创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);

            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 14);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 水平垂直居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
            contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            // 内容背景白色
            contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            WriteFont contentWriteFont = new WriteFont();

            // 内容字体大小
            contentWriteFont.setFontHeightInPoints((short) 12);
            contentWriteCellStyle.setWriteFont(contentWriteFont);

            //设置边框样式，细实线
            contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
            contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
            contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
            contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

            // 水平垂直居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle,
                    contentWriteCellStyle);

            // 写excel
            EasyExcel.write(tempFile.getPath(), SupplierUserExportResult.class)
                    // 自定义样式
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    // 自动列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    // 机构分组合并单元格
                    .registerWriteHandler(new CommonExcelCustomMergeStrategy(supplierUserExportResultList.stream().map(SupplierUserExportResult::getGroupName)
                            .collect(Collectors.toList()), 0))
                    // 设置第一行字体
                    .registerWriteHandler(new CellWriteHandler() {
                        @Override
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            WriteCellData<?> cellData = context.getFirstCellData();
                            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                            Integer rowIndex = context.getRowIndex();
                            if(rowIndex == 0) {
                                WriteFont headWriteFont = new WriteFont();
                                headWriteFont.setFontName("宋体");
                                headWriteFont.setBold(true);
                                headWriteFont.setFontHeightInPoints((short) 16);
                                writeCellStyle.setWriteFont(headWriteFont);
                            }
                        }
                    })
                    // 设置表头行高
                    .registerWriteHandler(new AbstractRowHeightStyleStrategy() {
                        @Override
                        protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
                            if(relativeRowIndex == 0) {
                                // 表头第一行
                                row.setHeightInPoints(34);
                            } else {
                                // 表头其他行
                                row.setHeightInPoints(30);
                            }
                        }
                        @Override
                        protected void setContentColumnHeight(Row row, int relativeRowIndex) {
                            // 内容行
                            row.setHeightInPoints(20);
                        }
                    })
                    .sheet("人员信息")
                    .doWrite(supplierUserExportResultList);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 人员导出异常：", e);
            CommonResponseUtil.renderError(response, "导出失败");
        } finally {
            FileUtil.del(tempFile);
        }
    }

    @Override
    public void exportUserInfo(SupplierUserIdParam supplierUserIdParam, HttpServletResponse response) throws IOException {
        File destTemplateFile = null;
        File resultFile = null;
        try {
            SupplierUser supplierUser = this.queryEntity(supplierUserIdParam.getId());
            transService.transOne(supplierUser);
            // 读取模板流
            InputStream inputStream = POICacheManager.getFile("userExportTemplate.docx");
            // 创建一个临时模板
            destTemplateFile = FileUtil.writeFromStream(inputStream, FileUtil.file(FileUtil.getTmpDir() +
                    File.separator + "userExportTemplate.docx"));
            // 构造填充的参数
            Map<String, Object> map = BeanUtil.beanToMap(supplierUser);
            String avatarBase64;
            if(ObjectUtil.isNotEmpty(supplierUser.getAvatar())) {
                avatarBase64 = supplierUser.getAvatar();
            } else {
                avatarBase64 = CommonAvatarUtil.generateImg(supplierUser.getName());
            }
            // 头像
            ImageEntity imageEntity = new ImageEntity(ImgUtil.toBytes(ImgUtil.toImage(StrUtil
                    .split(avatarBase64, StrUtil.COMMA).get(1)), ImgUtil.IMAGE_TYPE_PNG), 120, 160);
            map.put("avatar", imageEntity);
            if(ObjectUtil.isNotEmpty(supplierUser.getBirthday())) {
                try {
                    // 年龄
                    long age = DateUtil.betweenYear(DateUtil.parseDate(supplierUser.getBirthday()), DateTime.now(), true);
                    if(age != 0) {
                        map.put("age", age + "岁");
                    }
                } catch (Exception ignored) {
                }
            }
            // 导出时间
            map.put("exportDateTime", DateUtil.format(DateTime.now(), DatePattern.CHINESE_DATE_PATTERN));
            // 生成doc
            XWPFDocument doc = WordExportUtil.exportWord07(destTemplateFile.getAbsolutePath(), map);
            // 生成临时导出文件
            resultFile = FileUtil.file(FileUtil.getTmpDir() + File.separator + "SNOWY系统B端人员信息_" + supplierUser.getName() + ".docx");
            // 写入
            BufferedOutputStream outputStream = FileUtil.getOutputStream(resultFile);
            doc.write(outputStream);
            outputStream.close();
            // 下载
            CommonDownloadUtil.download(resultFile, response);
        } catch (Exception e) {
            log.error(">>> 导出人员个人信息异常：", e);
            CommonResponseUtil.renderError(response, "导出失败");
        } finally {
            // 删除临时文件
            if(ObjectUtil.isNotEmpty(destTemplateFile)) {
                FileUtil.del(destTemplateFile);
            }
            if(ObjectUtil.isNotEmpty(resultFile)) {
                FileUtil.del(resultFile);
            }
        }
    }

    @Override
    public SupplierUser queryEntity(String id) {
        SupplierUser supplierUser = this.getById(id);
        if(ObjectUtil.isEmpty(supplierUser)) {
            throw new CommonException("人员不存在，id值为：{}", id);
        }
        return supplierUser;
    }

    //循环的方法获取子角色列表
    public List<String> getChildRole(List<SupplierRole> roleList, List<String> parentRoleIds) {
        List<String> childRoldList = CollectionUtil.newArrayList();
        List<SupplierRole> newRoles = CollectionUtil.newArrayList();
        do {
            newRoles = roleList.stream().filter((item) -> {
                return parentRoleIds.contains(item.getParentId());
            }).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(newRoles)) {
                List<String> newRoleIds = new ArrayList<>();
                for (SupplierRole supplierRole : newRoles) {
                    newRoleIds.add(supplierRole.getId());
                }
                childRoldList.addAll(newRoleIds);
                parentRoleIds.clear();
                parentRoleIds.addAll(newRoleIds);
            }
        } while (ObjectUtil.isNotEmpty(newRoles));
        if (ObjectUtil.isNotEmpty(childRoldList)) {
            return childRoldList;
        } else {
            return new ArrayList<>();
        }

    }

    /* ====人员部分所需要用到的选择器==== */

    @Override
    public List<Tree<String>> orgTreeSelector() {
        LambdaQueryWrapper<SupplierOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        // 定义机构集合
        Set<SupplierOrg> supplierOrgSet = CollectionUtil.newHashSet();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<SupplierOrg> allOrgList = supplierOrgService.list();
            loginUserDataScope.forEach(orgId -> supplierOrgSet.addAll(supplierOrgService.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = supplierOrgSet.stream().map(SupplierOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(SupplierOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(SupplierOrg::getSortCode);
        List<SupplierOrg> supplierOrgList = supplierOrgService.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = supplierOrgList.stream().map(supplierOrg ->
                        new TreeNode<>(supplierOrg.getId(), supplierOrg.getParentId(), supplierOrg.getName(), supplierOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public Page<SupplierOrg> orgListSelector(SupplierUserSelectorOrgListParam supplierUserSelectorOrgListParam) {
        LambdaQueryWrapper<SupplierOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(SupplierOrg::getId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 查询部分字段
        lambdaQueryWrapper.select(SupplierOrg::getId, SupplierOrg::getParentId, SupplierOrg::getName,
                SupplierOrg::getCategory, SupplierOrg::getSortCode);
        if (ObjectUtil.isNotEmpty(supplierUserSelectorOrgListParam.getParentId())) {
            lambdaQueryWrapper.eq(SupplierOrg::getParentId, supplierUserSelectorOrgListParam.getParentId());
        }
        if (ObjectUtil.isNotEmpty(supplierUserSelectorOrgListParam.getSearchKey())) {
            lambdaQueryWrapper.like(SupplierOrg::getName, supplierUserSelectorOrgListParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(SupplierOrg::getSortCode);
        return supplierOrgService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }

    @Override
    public Page<SupplierPosition> positionSelector(SupplierUserSelectorPositionParam supplierUserSelectorPositionParam) {
        LambdaQueryWrapper<SupplierPosition> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(SupplierPosition::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 查询部分字段
        lambdaQueryWrapper.select(SupplierPosition::getId, SupplierPosition::getOrgId, SupplierPosition::getName,
                SupplierPosition::getCategory, SupplierPosition::getSortCode);
        if (ObjectUtil.isNotEmpty(supplierUserSelectorPositionParam.getOrgId())) {
            lambdaQueryWrapper.eq(SupplierPosition::getOrgId, supplierUserSelectorPositionParam.getOrgId());
        }
        if (ObjectUtil.isNotEmpty(supplierUserSelectorPositionParam.getSearchKey())) {
            lambdaQueryWrapper.like(SupplierPosition::getName, supplierUserSelectorPositionParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(SupplierPosition::getSortCode);
        return supplierPositionService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }

    @SuppressWarnings("ALL")
    @Override
    public Page<SupplierUserRoleResult> roleSelector(SupplierUserSelectorRoleParam supplierUserSelectorRoleParam) {
        //20250218 Mr.wu 修改人员管理中授权角色的角色选择器获取逻辑，原逻辑是按部门归属的角色进行上下级过滤，现改为根据创建者父子关系获取下级角色
        LambdaQueryWrapper<SupplierRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询部分字段
        lambdaQueryWrapper.select(SupplierRole::getId, SupplierRole::getOrgId, SupplierRole::getName,
                SupplierRole::getCategory, SupplierRole::getSortCode);
        //在此加入上下级过滤判断，即只显示由当前用户角色所创建的下级及子孙级角色，不显示自已的以及自己以上的
        //获取公司全部角色
        List<SupplierRole> allRoleList = supplierRoleService.list();
        //1、先获取操作员当前角色
        SupplierUserIdParam supplierUserIdParam = new SupplierUserIdParam();
        supplierUserIdParam.setId(StpLoginUserUtil.getLoginUser().getId());
        List<String> ownRoleList = this.ownRole(supplierUserIdParam);//获取当前用户的角色数组
        childRoldList = new ArrayList<>();
        List<String> childRoleIds =  getChildRole(allRoleList, ownRoleList);//获取下级角色数据
        if(ObjectUtil.isNotEmpty(childRoleIds)){
            lambdaQueryWrapper.in(SupplierRole::getId,childRoleIds);
            return BeanUtil.toBean(supplierRoleService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper), Page.class);
        }else{
            return new Page<>();
        }
    }

    @Override
    public Page<SupplierUser> userSelector(SupplierUserSelectorUserParam supplierUserSelectorUserParam) {
        LambdaQueryWrapper<SupplierUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(SupplierUser::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 只查询部分字段
        lambdaQueryWrapper.select(SupplierUser::getId, SupplierUser::getAvatar, SupplierUser::getOrgId, SupplierUser::getPositionId, SupplierUser::getAccount,
                SupplierUser::getName, SupplierUser::getSortCode, SupplierUser::getGender, SupplierUser::getEntryDate);
        if (ObjectUtil.isNotEmpty(supplierUserSelectorUserParam.getOrgId())) {
            // 如果机构id不为空，则查询该机构及其子机构下的所有人
            List<String> childOrgIdList = CollStreamUtil.toList(supplierOrgService.getChildListById(supplierOrgService
                    .getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId()), supplierUserSelectorUserParam.getOrgId(), true), SupplierOrg::getId);
            if (ObjectUtil.isNotEmpty(childOrgIdList)) {
                lambdaQueryWrapper.in(SupplierUser::getOrgId, childOrgIdList);
            } else {
                return new Page<>();
            }
        }
        // 排除超管
        lambdaQueryWrapper.ne(SupplierUser::getAccount, SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
        if (ObjectUtil.isNotEmpty(supplierUserSelectorUserParam.getSearchKey())) {
            lambdaQueryWrapper.like(SupplierUser::getName, supplierUserSelectorUserParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(SupplierUser::getSortCode);
        return this.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }
}
